package com.app.dao.impl;

import com.app.common.AppException;
import com.app.dao.IDepartmentDao;
import com.app.pojo.Department;
import com.app.utils.JDBCTemplate;
import com.app.utils.WhereCause;

import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * Copyright (C) @2020 fuguo.wang@logicsolutions.com.cn
 *
 * @author fuguo.wang
 * @version 1.0
 * @className DepartmentDao
 * @date 2020-06-18 23:13
 * @description
 */
public class DepartmentDao implements IDepartmentDao {

	private final JDBCTemplate jdbcTemplate = new JDBCTemplate();

	/**
	 * select * from XXXX 抽象方法
	 *
	 * @return 对象数据集合
	 */
	@Override
	public List<Department> select() {
		try {
			return jdbcTemplate.select(Department.class);
		} catch (SQLException e) {
			e.printStackTrace();
			throw new AppException(e);
		}
	}

	/**
	 * 查询单条数据
	 *
	 * @param id
	 * @return
	 */
	@Override
	public Department select(Integer id) {
		List<WhereCause> params = new ArrayList<>();
		params.add(new WhereCause()
				.setKey("id")
				.setCondition(WhereCause.EQUAL)
				.setValue(id));
		try {
			return jdbcTemplate.selectBean(Department.class, params);
		} catch (SQLException e) {
			throw new AppException(e);
		}
	}

	/**
	 * 新增单条记录
	 *
	 * @param department 数据对象
	 * @return 主键id
	 */
	@Override
	public Integer insert(Department department) {
		try {
			department
					.setDisable(false)
					.setCreatedTime(LocalDateTime.now())
					.setUpdateTime(LocalDateTime.now());
			return jdbcTemplate.insert(department);
		} catch (SQLException e) {
			e.printStackTrace();
			throw new AppException(e);
		}
	}

	/**
	 * 更新单条数据
	 *
	 * @param department
	 */
	@Override
	public void update(Department department) {
		try {
			department.setUpdateTime(LocalDateTime.now());
			jdbcTemplate.update(department);
		} catch (SQLException e) {
			e.printStackTrace();
			throw new AppException(e);
		}
	}

	/**
	 * 删除记录
	 *
	 * @param ids 支持一次删多条
	 */
	@Override
	public void delete(String ids) {
		List<WhereCause> params = new ArrayList<>();
		params.add(new WhereCause()
				.setKey("id")
				.setCondition(WhereCause.IN)
				.setValue(ids)
				.setNumber(true));
		try {
			jdbcTemplate.delete(Department.class, params);
		} catch (SQLException e) {
			throw new AppException(e);
		}
	}
}
